<?php
namespace app\admin\middleware;

use app\saas\model\trMall;
use app\common\util\ErrorCode;
use think\Response;

// 中间件
class Check
{
    public function handle($request, \Closure $next)
    {
        /*--- start 跨域用 ---*/
        header('Access-Control-Allow-Origin: *');                                    // 允许任意域名发起的跨域请求
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
        header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With,x_requested_with,x-requested-with,content-type');
        /*--- end 跨域用---*/
        $request->mallId = $request->mallId ? $request->mallId : 1;
//        if(in_array($request->routeInfo()["rule"], ["admin/role/login", "admin/getConfig"])) {
//            $request->mallId = $request->mallId ? $request->mallId : 1;
//        }
        if(empty($request->mallId)){
            return Response::create(ErrorCode::code("mall_id_not_exist"), 'json');
        }
        if(!$mallData = trMall::getCacheData($request->mallId)){
            db()->getConnection()->close(); // 关闭数据库连接
            return Response::create(ErrorCode::code("customized", "商城不存在"), 'json');
        }
        if (!empty($mallData["expiredTime"]) && $mallData["expiredTime"] <= time()) {
            return Response::create(ErrorCode::code("mall_expired"), 'json');
        }
        if($mallData["isDelete"] != "0"){
            return Response::create(ErrorCode::code("customized", "商城已回收"), 'json');
        }
        if($mallData["isDisable"] != "0"){
            return Response::create(ErrorCode::code("customized", "商城已禁用"), 'json');
        }
        if(!empty($request->manageData) && $request->manageData["type"] != '1' && $mallData["managerId"] != $request->manageData["id"]){ // 1 - 超级管理员。其它管理员要判断商城的拥有者
            db()->getConnection()->close(); // 关闭数据库连接
            return Response::create(ErrorCode::code("customized", "您无权限操作该商城"), 'json');
        }
        $request->mallData = $mallData;
        return $next($request);
    }
}
